package com.xpgk.xpsoft.login;

import java.util.Date;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.redis.Redis;
import com.xpgk.common.kit.CacheKitEx;
import com.xpgk.model.FrmUser;
import com.xpgk.xpsoft.common.XPSoftLog;
import com.xpgk.xpsoft.common.XPSoftService;
import com.xpgk.xpsoft.constants.XPSoftConstant;
import com.xpgk.xpsoft.user.UserService;

public class LoginService extends XPSoftService {
	
	public static String login(String userName, String password, String clientIp) {
		// 3.密码错误次数超限
//		long errorCount = UserService.getLoginErrNumber(userName);
		long errorCount = 0;
		if (errorCount >=10000) {
			if (CacheKitEx.IsUseRedis())
				Redis.use(XPSoftConstant.cacheName).expire(XPSoftConstant.cacheKey_UserID(userName), 1800);
			return "密码错误次数超过10000次，30分钟内不能登录。";
		}
		// 4.验证密码
		if (!UserService.validPassword(userName, password))
			return "用户名或密码错误。";

		// 2.停用账户
		String status = UserService.getUserState(userName);
		if (!status.equals("ok")) {
			return status;
		}

		status = UserService.getUserLimitIP(userName, clientIp);
		if (!status.equals("ok")) {
			return status;
		}

		Db.update("update FRM_USER set LASTLOGINIP = ?, LASTLOGINTIME = ? where USERNAME = ?", clientIp, new Date(), userName);
		FrmUser user = UserService.getUser(userName);
		if (user != null) // 1 改为登录
			XPSoftLog.write(user.getID(), "login", "USERNAME=" + userName, XPSoftConstant.log_login, 1, "登录",
					clientIp);
		return "ok";
	}

	static public void logout(String userName, String clientIp) {
		FrmUser user = UserService.getUser(userName);
		if (user != null) // 2 改为登出
			XPSoftLog.write(user.getID(), "logout", "USERNAME=" + userName, XPSoftConstant.log_login, 2, "登出",
					clientIp);
		UserService.removeAllCache(userName);
	}
}
